package com.fengqilin.projectlplc;

import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Client {
    private static final String TAG = Client.class.getName();
    static boolean isStart = false;
    private Socket socket;
    String[] attr = {
            // 校验值
            "01WRDD00107,01\r\n",
            // 停机状态
            "01WRDD00135,01\r\n",
            // 当前命令值
            "01WRDD02522,02\r\n",
            // 编码器反馈值
            "01WRDD02524,02\r\n",
            // 第几组
            "01WRDD00740,01\r\n",
            // 伺服号
            "01WRDD00112,01\r\n",
            // 微调值
            "01WRDD02516,02\r\n",
            // 微调状态
            "01BRDI00081,002\r\n",
            // 前进后退状态
            "01BRDI00112,002\r\n"
    };

    public Map<String, Integer> initKeyMap() {
        Map<String, Integer> map = new HashMap<>();
        map.put("D740", 4);
        map.put("D112", 5);
        map.put("D2516", 6);
        map.put("I81", 7);
        map.put("I82", 7);
        map.put("I112", 8);
        map.put("I113", 8);
        return map;
    }

    public String socket(String message) {
        if (!isStart) return "";
        // Log.d(TAG, "socket: " + message);
        if (socket != null && socket.isConnected() && !socket.isClosed()) {
            try {
                socket.close();
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        try {
            // 创建Socket对象，指定服务端的IP地址和端口号
            socket = new Socket("192.168.0.186", 12289);
            socket.setSoTimeout(5000);
            // 将用户输入的信息发送给服务端
            if (!TextUtils.isEmpty(message)) {
                OutputStream stream = socket.getOutputStream();
                stream.write(message.getBytes());
                stream.flush();
            }
            // 获取输入流和输出流 输入流和输出流是通过socket对象来进行数据传输的。
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            // 接收服务端的响应并打印
            String response = in.readLine();
            // 关闭连接
            in.close();
            socket.close();
            return response;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    private static final ExecutorService threadPool1 = Executors.newFixedThreadPool(1);
    //    private static final ExecutorService threadPool2 = Executors.newFixedThreadPool(1);
    private static final Client client = new Client();
    public static boolean isRunning = false;
    public static final PollingManager p = new PollingManager();

    public static void requestAll(final Callback callback) {
        threadPool1.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < client.attr.length; i++) {
                    String socket = client.socket(client.attr[i]);
                    // Log.d(TAG, "onCreate: " + socket);
                    callback.onResult(i, socket);
                    if (i == 0 && !TextUtils.isEmpty(socket) && !MainActivity.nowKey.equals(socket.substring(4))) {
                        break;
                    }
                }
                Client.p.callback = callback;
                p.resumePolling();
            }
        });
    }

    public static void requestOne(int index, final Callback callback) {
        threadPool1.execute(new Runnable() {
            @Override
            public void run() {
                String socket = client.socket(client.attr[index]);
                // Log.d(TAG, "onCreate: " + socket);
                callback.onResult(index, socket);
                if (index == 0 && !TextUtils.isEmpty(socket) && !MainActivity.nowKey.equals(socket.substring(4))) {
                    return;
                }
                Client.p.callback = callback;
                // 开始请求所有的状态信息的轮询
                p.resumePolling();
            }
        });
    }

    public static void request(String cmd, int index, final Callback callback) {
        // 结束轮询
        p.stopPolling();
        threadPool1.execute(new Runnable() {
            @Override
            public void run() {
                Log.d(TAG, "request: " + cmd);
                // 当前运行中
                isRunning = true;
                // 发送当前指令
                String socket = client.socket(cmd);
                // Log.d(TAG, "request: " + socket);
                // 请求所有的状态信息
                // requestAll(callback);
                // 请求当前指令的状态信息
                requestOne(index, callback);
                // 当前运行完成
                isRunning = false;
            }
        });
    }

    public interface Callback {
        void onResult(int i, String data);
    }

    public static Client inst() {
        return client;
    }
}
